package com.jims.master.modules.sys.utils.netease;


import com.jims.master.modules.base.user.entity.MasterBaseinfo;
import com.jims.master.modules.base.user.entity.MasterContactinfo;
import com.jims.master.modules.sys.entity.User;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.eclipse.jetty.util.ajax.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author WangYQ
 * @time 2016/3/7.
 */
public class NetEaseServerAPI {

    private static Logger logger = LoggerFactory.getLogger(NetEaseServerAPI.class);
//    智慧云健康平台网易云IM appkey 、appSecret
//    private static String appKey = "7a9d0b8982932a0cb71feeeeccabeb72";
//    private static String appSecret = "a7b45c0de917";
//    京顺医院测试
    private static String appKey = "6c22809f6e96d53525f133ce95a23514";
    private static String appSecret = "64f64b72479d";

//    private static String appKey = "6255433de2a6341858a65f25dd710d91";
//    private static String appSecret = "36ff597f2c8e";
    /**
     * 使用CURL方式发送post请求
     * @param  url     请求地址
     * @return
     */
    public static HttpPost postJsonDataCurl(String url){
        HttpPost httpPost = new HttpPost(url);
        String nonce = UUIDUtil.getUUID();
        String curTime = String.valueOf(System.currentTimeMillis() / 1000);
        String checksum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader( "Nonce", nonce);
        httpPost.addHeader( "CurTime", curTime);
        httpPost.addHeader( "CheckSum", checksum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        return httpPost;
    }
    /**
     * 创建云信ID
     * 1.第三方帐号导入到云信平台；
     * 2.注意accid，name长度以及考虑管理秘钥token
     * @param  accid     [云信ID，最大长度32字节，必须保证一个APP内唯一（只允许字母、数字、半角下划线_、@、半角点以及半角-组成，不区分大小写，会统一小写处理）]
     * @param  name      [云信ID昵称，最大长度64字节，用来PUSH推送时显示的昵称
     * @return token    [返回登录token]
     */
    public static String createUser(String accid,String name){

        String url = "https://api.netease.im/nimserver/user/create.action";
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String httpEntity=null;
        try {
            // addHeader
            HttpPost httpPost=postJsonDataCurl(url);
            String token = UUIDUtil.getUUID();
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("accid", accid));
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("token", token));
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 打印执行结果
            httpEntity= EntityUtils.toString(response.getEntity(), "utf-8");
            logger.debug(httpEntity.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpEntity;
    }
    /**
     * 更新云信ID
     * @param  accid     [云信ID，最大长度32字节，必须保证一个APP内唯一（只允许字母、数字、半角下划线_、@、半角点以及半角-组成，不区分大小写，会统一小写处理）]
     * @param  token     [云信ID可以指定登录token值，最大长度128字节，并更新，如果未指定，会自动生成token，并在创建成功后返回]
     * @return httpEntity    [返回httpEntity对象]
     */
    public static String updateUserID(String accid,String props,String token){
        String result=null;
        String url="https://api.netease.im/nimserver/user/update.action";
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String httpEntity=null;
        try {
            // addHeader
            HttpPost httpPost=postJsonDataCurl(url);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("accid", accid));
            params.add(new BasicNameValuePair("token", token));
            params.add(new BasicNameValuePair("props", props));
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 打印执行结果
            httpEntity= EntityUtils.toString(response.getEntity(), "utf-8");
            logger.debug(httpEntity.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpEntity;
    }
    /**
     * 更新并获取新token
     * @param  accid     [云信ID，最大长度32字节，必须保证一个APP内唯一（只允许字母、数字、半角下划线_、@、半角点以及半角-组成，不区分大小写，会统一小写处理）]
     * @return HttpEntity    [返回HttpEntity对象]
     */
    public static String updateUserToken(String accid){

        String url="https://api.netease.im/nimserver/user/refreshToken.action";
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String httpEntity=null;
        try {
            // addHeader
            HttpPost httpPost=postJsonDataCurl(url);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("accid", accid));
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 打印执行结果
            httpEntity= EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(httpEntity);
            logger.debug(httpEntity.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpEntity;
    }
    /**
     * 好友关系-加好友
     * @param  accid       [云信ID，最大长度32字节，必须保证一个APP内唯一（只允许字母、数字、半角下划线_、@、半角点以及半角-组成，不区分大小写，会统一小写处理）]
     * @param  faccid        [云信ID昵称，最大长度64字节，用来PUSH推送时显示的昵称]
     * @param  msg        [用户签名，最大长度256字节]
     * @return httpEntity      [返回httpEntity字符串]
     */
    public static String addFriend(String accid,String faccid,String msg){
        String type=1+"";
        String url="https://api.netease.im/nimserver/friend/add.action";
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String httpEntity=null;
        try {
            HttpPost httpPost=postJsonDataCurl(url);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("accid", accid));
            params.add(new BasicNameValuePair("faccid", faccid));
            params.add(new BasicNameValuePair("type", type));
            params.add(new BasicNameValuePair("msg", msg));
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 执行结果
            httpEntity= EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(httpEntity);
            logger.debug(httpEntity.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return httpEntity;
    }

    /**
     * 好友关系-删除好友信息
     * @param  accid       [云信ID，最大长度32字节，必须保证一个APP内唯一（只允许字母、数字、半角下划线_、@、半角点以及半角-组成，不区分大小写，会统一小写处理）]
     * @param  faccid        [要修改朋友的accid]
     * @return httpEntity      [返回httpEntity字符串]
     */
    public static String deleteFriend(String accid,String faccid){
        String url="https://api.netease.im/nimserver/friend/delete.action";
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String httpEntity=null;
        try {
            HttpPost httpPost=postJsonDataCurl(url);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("accid", accid));
            params.add(new BasicNameValuePair("faccid", faccid));
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 打印执行结果
            httpEntity= EntityUtils.toString(response.getEntity(), "utf-8");
            logger.debug(httpEntity.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpEntity;
    }
    /**
     * 更新用户名片
     * @param  accid       [云信ID，最大长度32字节，必须保证一个APP内唯一（只允许字母、数字、半角下划线_、@、半角点以及半角-组成，不区分大小写，会统一小写处理）]
     * @param  name        [云信ID昵称，最大长度64字节，用来PUSH推送时显示的昵称]
     * @param  icon        [用户icon，最大长度256字节]
     * @param  sign        [用户签名，最大长度256字节]
     * @param  email       [用户email，最大长度64字节]
     * @param  birth       [用户生日，最大长度16字节]
     * @param  mobile      [用户mobile，最大长度32字节]
     * @param  gender      [用户性别，0表示未知，1表示男，2女表示女，其它会报参数错误]
     * @return httpEntity      [返回httpEntity字符串]
     */
    public static String updateUserInfo(String accid,String name,String icon,String sign,String email,String birth,String mobile,int gender){
        String url="https://api.netease.im/nimserver/user/updateUinfo.action";
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String httpEntity=null;
        try {
            HttpPost httpPost=postJsonDataCurl(url);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("accid", accid));
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("icon", icon));
            params.add(new BasicNameValuePair("sign", sign));
            params.add(new BasicNameValuePair("email", email));
//            params.add(new BasicNameValuePair("birth", birth));
            params.add(new BasicNameValuePair("mobile", mobile));
            params.add(new BasicNameValuePair("gender", gender+""));
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 打印执行结果
            httpEntity= EntityUtils.toString(response.getEntity(), "utf-8");
            logger.debug(httpEntity.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpEntity;
    }
    /*
   * 把HttpEntity对象转化成字符串数组
   * @param  strs  HttpEntity对象字符串
   * @return arr  数组
   * */
    public static String[] getResult(String strs) throws IOException {
        String[] arr=strs.split("\"");
        logger.debug(arr.toString());
        return arr;
    }
    /*
    * 判断用户在网易即时通讯上是否注册
    * @param  arr  字符串数组
    * @return boolean  判断是否注册
    * */
    public static boolean isRegister(String[] arr){
        int len=arr.length;
        if(len<=7){
            return true;
        }else {
            /*String code=arr[6].substring(1,4);*/
            return false;
        }
    }
    /*
    * 判断是否注册成功/token更新成功
    * @param  map
    * @return boolean
    * */
    public static boolean isRegistNetease(Map<Object,Object> map){
        String code=map.get("code").toString();
        if("200".equals(code)){
            return true;
        }else{
            return false;
        }
    }
    /*
    * 将把HttpEntity对象转化成map集合
    * @param  str HttpEntity对象的字符串
    * @return map
    * */
    public static Map<Object,Object> toMap(String str){
        Object json=JSON.parse(str);
        Map<Object,Object> map = (Map)json;
        return map;
    }
    /*
    * 获取token
    * @param  map HttpEntity对象的map集合
    * @return token
    * */
    public static String getToken(Map<Object,Object> map){
        Map info=(Map) map.get("info");
        String token=info.get("token").toString();
        return token;
    }
    /**
     * 更新用户名片
     * @param  user
     * @param  masterBaseinfo
     * @param  masterContactinfo
     * @return boolean
     */
    public static boolean updateNeteaseUserInfo(User user, MasterBaseinfo masterBaseinfo, MasterContactinfo masterContactinfo){
//        MasterBaseinfo masterBaseinfo=masterBaseinfoService.get(user.getPersionId());
//        MasterContactinfo masterContactinfo=masterContactinfoService.getContactinfoByBasId(masterBaseinfo.getId());
//		accid       [云信ID，最大长度32字节，必须保证一个APP内唯一（只允许字母、数字、半角下划线_、@、半角点以及半角-组成，不区分大小写，会统一小写处理）]
        String accid="";
//		数据库user表中id不一样长
        if(user.getId().length()<32){
            accid=user.getId();
        }else {
            accid=(user.getId()).substring(0,32);
        }
//		name        [云信ID昵称，最大长度64字节，用来PUSH推送时显示的昵称]
        String name=masterBaseinfo.getName();
//		icon        [用户icon，最大长度256字节]
        String icon=masterBaseinfo.getHeadPath();
//		sign        [用户签名，最大长度256字节]
        String sign="关注健康，关爱生命！";
//		[用户email，最大长度64字节]
        String email=masterContactinfo.getEmail();
//		birth       [用户生日，最大长度16字节]
        String birth=null;
//		mobile      [用户mobile，最大长度32字节]
        String mobile=masterContactinfo.getMobilePhone();
//		gender      [用户性别，0表示未知，1表示男，2女表示女，其它会报参数错误]
        String sex=masterBaseinfo.getSex();
        int gender=0;
        if(sex==null||"".equals(sex)){
            gender=0;
        }else{
            gender=Integer.parseInt(sex);
        }
        String httpEntity= updateUserInfo(accid,name,icon,sign,email,birth,mobile,gender);
        return isRegistNetease(NetEaseServerAPI.toMap(httpEntity));
    }
    public static void main(String[] args) {
        String wa = createUser("5185659a46cb4099a56322c8dc629e5e".substring(0,32),"cheng");
        System.out.print(wa);
    }
}
